<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class Integral extends Controller {
    static protected $err_code = 0;
    // 获取账户摩豆数量接口
    static public function get_integral_count($param) {
        if(!isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $integral = Db::table('mob_integral')->where('member_id', $param['member_id'])->sum('num');
            return ['data' => ['integral' => $integral?$integral:0 ], 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取账户摩豆记录接口
    static public function get_integral_list($param) {
        if(!isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $integrals = Db::table('mob_integral')->where('member_id', $param['member_id'])->paginate();
            return ['data'=>$integrals, 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['data'=>'', 'code'=>0, 'msg'=> $e->getMessage()];
        }
    }

    // 添加摩豆接口
    static public function add_integral($param) {
        if(!isset($param['member_id']) || !isset($param['num']) || !isset($param['msg'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            $data = [
                'member_id' => $param['member_id'],
                'num' => $param['num'],
                'msg' => $param['msg'],
                'add_time' => time(),
            ];
            Db::table('mob_integral')->insert($data);
            Db::commit();
            return ['code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['data'=>'', 'code'=>0, 'msg'=> $e->getMessage()];
        }
    }
}
